<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/11
 * Time: 15:04
 */

namespace app\api;


use think\Controller;
use think\Db;

class Common extends Controller{

    /**
     * headers 信息
     * @var string
     */
    public $headers = '';



    public function _initialize()
    {
//        $headers = request()->header();
//        if($headers['check']==1){
//            //验签
//            $this->checkRequestAuth();
//        }
    }

    public function checkRequestAuth()
    {
        //$headers = input('get.');  这个只能获取到 ?id=1&age=18&sex=男 的这种类型的参数
        //$headers = Request::instance()->param();  // 这个能获取到  id/1/name/lbj/age/34/sex/男 的这种类型的参数

        $headers = request()->header();
        if(empty($headers['sign']))
        {
            return_json(0,'缺少sign');
        }
        $raw_sign = $headers['sign'];    //获取客户端传进来的sign
        unset($headers['sign']);         //注销掉sign参数*/

        $encsign = $this->getHeaderBaseParam($headers);
        if($encsign != $raw_sign)
        {
            return_json(0,'授权码sign失败');
        }
        $this->headers = $headers;
    }

    /**
     * 检查header头里要加密的基本参数是否缺少并进行加密
     * @param $baseParam
     * @return string
     * @throws ApiException
     */
    protected function getHeaderBaseParam($baseParam)
    {
        if(!isset($baseParam['uid']))
        {
            return_json(0,'缺少uid');
        }
        if(!isset($baseParam['appid']))
        {
            return_json(0,'缺少appid');
        }
        if(!isset($baseParam['pt']) && !empty($baseParam['pt']))
            {
            return_json(0,'缺少pt');
        }
        if(!isset($baseParam['imei']) || empty($baseParam['imei']))
        {
            return_json(0,'缺少imei');
        }
        if(!isset($baseParam['ver']) || empty($baseParam['ver']))
        {
            return_json(0,'缺少ver');
        }
        if(!isset($baseParam['t']) || empty($baseParam['t']))
        {
            return_json(0,'缺少t');
        }

        $uid = $baseParam['uid'];
        $pt = $baseParam['pt'];
        $imei = $baseParam['imei'];
        $ver = $baseParam['ver'];
        $appid = $baseParam['appid'];
        $t = $baseParam['t'];
        $md5Arr = [
            'uid'=>$uid,
            'pt'=>$pt,
            'imei'=>$imei,
            'ver'=>$ver,
            'appid'=>$appid,
            't'=>$t
        ];
        $sign = encrypt_md5($md5Arr,config('app.signkey'));
        return $sign;
    }
}